package kr.hkit.androidcomplete02.ch19;

import kr.hkit.androidcomplete02.R;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;

public class HandlerDivideEx extends Activity {
	int mainValue;
	TextView mainTv;
	TextView backTv;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch19_threadtest);
	
		mainTv = (TextView)findViewById(R.id.ch19_mainvalue);
		backTv = (TextView)findViewById(R.id.ch19_backvalue);
		
		BackThread thread = new BackThread(mHandler);
		thread.setDaemon(true);
		thread.start();
	}
	// 핸들러 생성
	Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			if(msg.what == 0){
				backTv.setText("BackValue : " + msg.arg1);
			}
		}
		
	};
	

	public void mOnClick(View v) {

		if (v.getId() == R.id.ch19_increase) {
			mainValue++;
			mainTv.setText("MainValue : " + mainValue);
		}
	}

	
}


class BackThread extends Thread{
	int mBackValue = 0;
	Handler mHandler;
	
	// 생성자에서 초기화
	public BackThread(Handler mHandler) {
		this.mHandler = mHandler;
	}

	@Override
	public void run() {
		while (true) {
			mBackValue++;

			// 매번 Message 객체를 생성하므로 메모리 낭비 !!
			
			/*Message msg = new Message();
			msg.what = 0;
			msg.arg1 = mBackValue;
			mHandler.sendMessage(msg);*/
			
			// 한번 생성한 Message 객체에 수정만 해서 사용.
			Message msg = Message.obtain(mHandler, 0, mBackValue, 0);
			mHandler.sendMessage(msg);

			try {
				sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	
}